import { ShelfStudyPlan } from '@/api/Shelf';
import { CityPicker } from '@/components/CityPicker';
import { CityPickerValue } from '@/components/CityPicker/interface';
import { getValueByCode } from '@/components/CityPicker/utils';
import { CoursewaresList } from '@/components/CoursewaresList';
import { SourceSelectModal } from '@/components/SourceSelect';
import Source from '@/components/SourceSelect/Entity/Source';
import TradeGroupSelect from '@/components/TradeGroupSelect';
import { TradeType } from '@/components/TradeGroupSelect/IndustrySel';
import { useRequest } from 'ahooks';
import type { UploadFile } from 'antd';
import { App, Button, Card, Cascader, Checkbox, Empty, Form, Input, Radio, Select, Space } from 'antd';
import React, { useMemo, useState } from 'react';
import { useYmAliOss, YmAddPageLayout, YmUpload, type YmAddPageLayoutProps } from 'ym-design';
export interface AddEditPorps {
  faceImg?: string;
  planName?: string;
  cycleType?: string;
  cycleDay?: string;
  learnObj?: string;
  learnMode?: string;
  planId?: string;
  region: string;
  regionName: string;
  entTypeCode: string;
  trade: string;
  showTrade: string;
  tradeName: string;
  isCharge: number;
  onBack?(): void;
}
export type tradeObj = {
  showTrade: TradeType[];
  tradeName: string;
  code: string;
};
type FormValue = {
  coursewares: Source[][];
  planName: string;
  cycleType: string;
  cycleDay: string;
  learnObj?: string;
  learnMode: string;
  faceImg?: UploadFile[];
  region: string[][] | string;
  regionName: string[] | string;
  entTypeCode: string[] | string;
  trade: string;
  showTrade: TradeType[] | string;
  tradeName: string;
  isCharge: number;
};
type setp1FormValue = {
  planName: string;
  cycleType: string;
  cycleDay?: string;
  learnObj?: string;
  learnMode: string;
  faceImg?: UploadFile[];
  region: string;
  regionName: string;
  entTypeCode: string;
  trade: string;
  tradeName: string;
  showTrade: TradeType[];
};
const pageContext = React.createContext('default');
export { pageContext };

const { PaneItem } = YmAddPageLayout;

export function AddEdit({ onBack, planId, ...formValue }: AddEditPorps) {
  const [current, setCurrent] = useState(0);
  const { message } = App.useApp();
  const [form] = Form.useForm<FormValue>();
  const region = Form.useWatch('region', form) ?? 'ALL';
  const [modalOpen, setModalOpen] = useState<number>();
  const [initValue] = useState<Partial<FormValue>>(() => {
    if (planId) {
      const { faceImg, region, entTypeCode, showTrade, isCharge, cycleDay, ...value } = formValue;
      const cycleOption = ['1', '2', '3', '5', '7'];
      const aa = {
        coursewares: [],
        faceImg: faceImg ? [{ url: faceImg, uid: faceImg, name: '封面' }] : [],
        region: (region ? region.split(',') : []).map<string[]>((regionCode) => {
          const aa = getValueByCode(regionCode, 'area')?.path as string[];
          return aa || 'ALL';
        }),
        entTypeCode: entTypeCode ? entTypeCode.split(',') : [],
        showTrade: showTrade ? JSON.parse(showTrade) : [],
        isCharge: isCharge,
        cycleDay: cycleDay && cycleOption.includes(String(cycleDay)) ? String(cycleDay) : '5',
        ...value,
      };
      console.log(aa.region);
      return aa;
    } else {
      return {
        cycleType: 'cycle',
        learnMode: 'order',
        cycleDay: '1',
        // learnObj: getStudyObjectDefaultAll(),
        coursewares: [],
        region: 'ALL',
        regionName: ['全部'],
        entTypeCode: [],
        trade: '',
        showTrade: [],
        tradeName: '',
        isCharge: undefined,
      };
    }
  });
  const cycleType = Form.useWatch('cycleType', form);
  const { modal } = App.useApp();
  const customRequest = useYmAliOss();
  //step下一页之后表单数据会取不到，先存一下
  const [formParams, setFormParam] = useState<setp1FormValue>({
    planName: '',
    cycleType: '',
    cycleDay: undefined,
    learnMode: '',
    faceImg: undefined,
    region: '',
    regionName: '',
    entTypeCode: '',
    tradeName: '',
    trade: '',
    showTrade: [],
  });

  const steps = [
    {
      title: '',
      content: (
        <>
          <Card title="创建学习计划模版" style={{ marginBottom: 16 }}>
            <Form.Item label="计划名称" name="planName" rules={[{ required: true }]} preserve={true}>
              <Input showCount maxLength={18} placeholder="请填写计划名称"></Input>
            </Form.Item>
            <Form.Item label="类型" required preserve={true}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
                <Form.Item name="cycleType" noStyle>
                  <Radio.Group disabled={planId ? true : false}>
                    <Radio value="cycle">周期循环</Radio>
                    <Radio value="fixed">固定时间</Radio>
                  </Radio.Group>
                </Form.Item>
                {cycleType !== 'fixed' ? (
                  <div hidden={cycleType !== 'cycle'} style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
                    每
                    <Form.Item name="cycleDay" noStyle rules={[{ required: true, message: '周期循环为空' }]}>
                      <Select
                        style={{ width: 60 }}
                        options={[
                          { value: '1', label: '1' },
                          { value: '2', label: '2' },
                          { value: '3', label: '3' },
                          { value: '5', label: '5' },
                          { value: '7', label: '7' },
                        ]}
                      />
                    </Form.Item>
                    日一学
                  </div>
                ) : null}
              </div>
            </Form.Item>
            {cycleType !== 'fixed' ? (
              <Form.Item label="学习机制" name="learnMode" rules={[{ required: true }]} preserve={true}>
                <Radio.Group>
                  <Radio value="order">顺序轮学</Radio>
                  <Radio value="polling">随机抽学</Radio>
                </Radio.Group>
              </Form.Item>
            ) : null}
            {/* <Form.Item label="学习对象" name="learnObj" rules={[{ required: true, message: '请选择学习对象' }]}>
              <StudyObjectCheckBoxGroup />
            </Form.Item> */}
            <Form.Item label="封面图" preserve={true}>
              <Space size={20}>
                <Form.Item name="faceImg" noStyle rules={YmUpload.formRules(false)}>
                  <YmUpload maxCount={1} cardWidth={375} cardHeight={200} customRequest={customRequest}>
                    请上传封面
                  </YmUpload>
                </Form.Item>
                <div>
                  <p>图片仅支持jpg、png格式 </p>
                  <p> 图片大小750*400 </p>
                </div>
              </Space>
            </Form.Item>
          </Card>
          <Card title="目标范围" bodyStyle={{ display: 'flex', flexDirection: 'column' }}>
            <Form.Item label="城市地域" required rules={[{ required: true, message: '选择城市地域' }]} preserve={true}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
                <Checkbox
                  style={{ flexShrink: 0 }}
                  checked={region === 'ALL' || region[0] === 'ALL'}
                  onChange={(value) => {
                    if (value.target.checked) {
                      form.setFieldsValue({
                        region: 'ALL',
                        regionName: '全部',
                      });
                    } else {
                      form.setFieldsValue({
                        region: [],
                        regionName: [],
                      });
                    }
                  }}
                >
                  全部
                </Checkbox>
                <Form.Item
                  style={{ flexGrow: 1 }}
                  name="region"
                  preserve={true}
                  noStyle
                  getValueFromEvent={(value, options: CityPickerValue[][]) => {
                    console.log(value);
                    form.setFieldsValue({
                      regionName: options.map((v) => v[v.length - 1]).map((v) => v.label),
                    });
                    return value;
                  }}
                  getValueProps={(value) => {
                    console.log(value, 'getValueProps');
                    return {
                      value,
                    };
                  }}
                  rules={[{ required: true, message: '请选择城市地域' }]}
                >
                  {region === 'ALL' || region[0] == 'ALL' ? (
                    <span></span>
                  ) : (
                    <CityPicker showCheckedStrategy={Cascader.SHOW_CHILD} multiple />
                  )}
                </Form.Item>
              </div>
            </Form.Item>
            <Form.Item hidden name="regionName" preserve={true}>
              <span></span>
            </Form.Item>
            <Form.Item
              label="组织类型"
              name="entTypeCode"
              rules={[{ required: true, message: '请选择组织类型' }]}
              preserve={true}
            >
              <Checkbox.Group>
                <Checkbox value="government">政府</Checkbox>
                <Checkbox value="association">协会</Checkbox>
                <Checkbox value="qiye">企业</Checkbox>
              </Checkbox.Group>
            </Form.Item>
            <Form.Item
              label="所属行业"
              name="showTrade"
              preserve={true}
              rules={[{ required: true, message: '请选择所属行业' }]}
            >
              <TradeGroupSelect
                // defaultValue={form.getFieldValue('showTrade') || []}
                onChange={(e: tradeObj) => {
                  form.setFieldsValue({
                    trade: e.code,
                    tradeName: e.tradeName,
                    showTrade: e.showTrade,
                  });
                }}
              />
            </Form.Item>
            <Form.Item
              preserve={true}
              hidden
              label="所属行业tradeName"
              name="tradeName"
              rules={[{ required: true, message: '请选择所属行业' }]}
            ></Form.Item>
            <Form.Item
              preserve={true}
              hidden
              label="所属行业trade"
              name="trade"
              rules={[{ required: true, message: '请选择所属行业' }]}
            ></Form.Item>
          </Card>
        </>
      ),
    },
    {
      title: '',
      content: (
        <>
          <Card
            title="选择课件"
            extra={
              <Button
                type="text"
                onClick={async () => {
                  const { coursewares: _coursewares } = await form.validateFields();
                  if (_coursewares.length >= 20) {
                    message.error('计划最多添加20个课件包');
                    return;
                  }
                  setModalOpen(Math.random());
                }}
              >
                选择
              </Button>
            }
            bodyStyle={{ display: 'flex', flexDirection: 'column', gap: 20 }}
          >
            {current == 1 ? (
              <Form.List name="coursewares">
                {(fields = [], { add, remove }) => {
                  let render = <Empty image={Empty.PRESENTED_IMAGE_DEFAULT} description="暂未选择任何课件" />;
                  if (fields.length) {
                    render = (
                      <>
                        {fields.map(({ name, key }, index) => {
                          // 如果删除到没有课件了,那么就删除掉课件包
                          const getValueFromEvent = (value: Source[]) => {
                            if (!value || value.length === 0) {
                              window.queueMicrotask(() => {
                                remove(index);
                              });
                            }
                            return value;
                          };
                          return (
                            <Card
                              title={'课件包' + (index + 1)}
                              type="inner"
                              key={key}
                              extra={
                                <Button
                                  type="text"
                                  onClick={() => {
                                    remove(index);
                                  }}
                                >
                                  删除
                                </Button>
                              }
                            >
                              <Form.Item name={name} noStyle getValueFromEvent={getValueFromEvent}>
                                <CoursewaresList></CoursewaresList>
                              </Form.Item>
                            </Card>
                          );
                        })}
                      </>
                    );
                  }
                  const formparams = form ? form.getFieldsValue(true) : {};
                  const paramsObj = {
                    entTypeCode: Array.isArray(formparams.entTypeCode)
                      ? formparams.entTypeCode.join(',')
                      : formparams.entTypeCode,
                    region: Array.isArray(formparams.region) ? formparams.region.join(',') : formparams.region,
                    trade: Array.isArray(formparams.trade) ? formparams.trade.join(',') : formparams.trade,
                  };
                  return (
                    <>
                      {render}
                      <pageContext.Provider value="planTemp">
                        <SourceSelectModal
                          openDep={modalOpen}
                          preSet="已上架课件"
                          params={paramsObj}
                          onChange={(data) => {
                            console.log('有没有收费', data && data[0].isCharge);
                            if (data && data[0].type === '课件包') {
                              Source.listWithRelationType('package', data[0].id).then((courseData) => {
                                if (!courseData.length) {
                                  modal.confirm({
                                    title: '提示',
                                    content: '该课件包没有内容请重新选择！',
                                  });
                                  return;
                                }
                                const newdata = JSON.parse(JSON.stringify(courseData));
                                newdata.map((v: { parentType: string; isCharge: number; packageId: string }) => {
                                  v.parentType = '课件包';
                                  v.isCharge = data[0].isCharge || 0;
                                  v.packageId = data[0].id;
                                });
                                add(newdata);
                              });
                            } else {
                              add(data);
                            }
                          }}
                        ></SourceSelectModal>
                      </pageContext.Provider>
                    </>
                  );
                }}
              </Form.List>
            ) : null}
          </Card>
        </>
      ),
    },
  ];
  useRequest(
    async () => {
      if (planId) {
        return Source.listWithRelationType('learn', planId, initValue.isCharge);
      }
    },
    {
      ready: Boolean(planId),
      onSuccess(data) {
        const result: Source[][] = [];
        data?.reduce((a, b) => {
          const origin = b.origin as any;
          const aArr = (a[origin.sortNum - 1] ??= []);
          if (origin.coursewareSortNum) {
            aArr[origin.coursewareSortNum - 1] = b;
          } else {
            aArr.push(b);
          }
          return a;
        }, result);
        form.setFieldsValue({ coursewares: result });
      },
    },
  );

  const items = steps.map((item) => ({ key: item.title, title: item.title }));
  const { run, loading } = useRequest(ShelfStudyPlan.createOrUpdate, {
    manual: true,
    onSuccess(e) {
      console.log('eeeee', e);
      onBack?.();
    },
  });

  //上架计划
  const upPlan = async (guid: string) => {
    await ShelfStudyPlan.shelf.upper({ guid: guid });
    onBack?.();
  };
  //保存计划
  const savePlan = async (isUp?: any) => {
    const { coursewares: _coursewares } = await form.validateFields();
    const { faceImg: _faceImg, showTrade, ...value } = formParams;
    let i = 0;
    const coursewareList = _coursewares.reduce((a, b) => {
      a.push(
        ...b.map((v, index) => {
          return {
            packageId: v.packageId || '',
            coursewareId: v.id,
            coursewareSortNum: index + 1,
            sortNum: i + 1,
            isCharge: v.isCharge || 0,
          };
        }),
      );
      i++;
      return a;
    }, [] as { packageId: string; coursewareId: string; coursewareSortNum: number; sortNum: number; isCharge: number }[]);
    //是否有收费课件
    let isCharge = 0;
    for (let j = 0; j < coursewareList.length; j++) {
      if (coursewareList[j].isCharge == 1) {
        isCharge = 1;
        break;
      }
    }
    //showTrade转字符串给后台
    const params = {
      ...value,
      coursewares: coursewareList,
      showTrade: JSON.stringify(showTrade),
      faceImg: _faceImg?.map((v) => v.response ?? v.url).join(','),
      planId,
      isCharge: isCharge,
    };
    if (params.coursewares.length === 0) {
      message.error('请选择学习内容');
      return;
    }
    if (_coursewares.length > 20) {
      message.error('计划最多添加20个课件包');
      return;
    }
    if (isUp) {
      const id = await ShelfStudyPlan.createOrUpdatePlan(params); //不是编辑进来调的话会返回id，编辑进来已经有planid了后台就不返回id了
      const guid = planId ? planId : id;
      if (guid && typeof guid === 'string') {
        upPlan(guid);
      }
    } else {
      run(params);
    }
  };

  //下一步
  const nextSub = async () => {
    try {
      await form.validateFields();
      const formAllVlue = JSON.parse(JSON.stringify(await form.validateFields()));
      //编辑的时候 如果目标范围变了 就清空课件
      if (planId) {
        let isChage = false;
        if (JSON.stringify(formAllVlue.region) != JSON.stringify(initValue.region)) {
          isChage = true;
        } else if (JSON.stringify(formAllVlue.entTypeCode) != JSON.stringify(initValue.entTypeCode)) {
          isChage = true;
        } else if (JSON.stringify(formAllVlue.showTrade) != JSON.stringify(initValue.showTrade)) {
          isChage = true;
        }
        if (isChage) {
          form.setFieldsValue({
            coursewares: [],
          });
        }
      }
      formAllVlue.regionName = Array.isArray(formAllVlue.regionName)
        ? formAllVlue.regionName.join(',')
        : formAllVlue.regionName;

      if (formAllVlue.region === 'ALL') {
        //区域选的全部不处理
      } else if (Array.isArray(formAllVlue.region) && formAllVlue.region.length == 1) {
        //区域选的全部数组的话要转字符串
        if (formAllVlue.region[0] === 'ALL') {
          formAllVlue.region = formAllVlue.region.join(',');
        }
      } else {
        formAllVlue.region = Array.isArray(formAllVlue.region)
          ? formAllVlue.region
              .map((v: string[]) => {
                return v[2] ?? v[1];
              })
              .join(',')
          : formAllVlue.region;
      }

      formAllVlue.entTypeCode = Array.isArray(formAllVlue.entTypeCode)
        ? formAllVlue.entTypeCode.join(',')
        : formAllVlue.entTypeCode;

      setFormParam(formAllVlue);
      setCurrent(current + 1);
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  };
  //上一步
  const prevSub = async () => {
    const { coursewares: _coursewares } = await form.validateFields();
    if (_coursewares.length != 0) {
      modal.confirm({
        title: '提示',
        content: '返回上一步后，所选的课件将被清空，确定返回？',
        async onOk() {
          form.setFieldsValue({
            coursewares: [],
          });
          setCurrent(current - 1);
        },
      });
    } else {
      setCurrent(current - 1);
    }
  };
  //保存
  const saveSub = () => {
    savePlan();
  };
  //上架
  const saveAndUpSub = () => {
    savePlan(1);
  };

  const operationFooter = useMemo(() => {
    if (current < steps.length - 1) {
      const operationBtn = [
        <Button key="next" type="primary" size="small" disabled={loading} onClick={nextSub}>
          下一步
        </Button>,
      ];
      return operationBtn;
    } else {
      const operationBtn = [
        <Button key="prev" type="dashed" size="small" disabled={loading} onClick={prevSub}>
          上一步
        </Button>,
        <Button key="save" type="default" size="small" disabled={loading} onClick={saveSub}>
          保存
        </Button>,
        <Button key="waiton" type="primary" size="small" disabled={loading} onClick={saveAndUpSub}>
          上架
        </Button>,
      ];
      return operationBtn;
    }
  }, [current, steps]);

  const layoutParams: YmAddPageLayoutProps = useMemo(
    () => ({
      leftOperation: {
        onBack: () => {
          onBack?.();
        },
      },
      rightOperationDom: operationFooter,
      destroyInactiveTabPane: false,
    }),
    [operationFooter],
  );

  return (
    <YmAddPageLayout {...layoutParams}>
      <PaneItem tabKey="tab1" label={current < steps.length - 1 ? '第一步' : '第二步'} className="pane_tab1">
        <div style={{ height: '100%', overflow: 'auto' }}>
          <Form form={form} labelCol={{ style: { width: 100 } }} preserve initialValues={initValue}>
            <div>{steps[current].content}</div>
          </Form>
        </div>
      </PaneItem>
    </YmAddPageLayout>
    // <YmAddPageLayout
    //   title={
    //     planId ? (
    //       <Steps className={planSty.stepCla} current={current} items={items} />
    //     ) : (
    //       <Steps className={planSty.stepCla} current={current} items={items} />
    //     )
    //   }
    //   onBack={onBack}
    //   items={current < steps.length - 1 ? firstBtns : secondBtns}
    // >
    //   <div style={{ height: '100%', overflow: 'auto' }}>
    //     <Form form={form} labelCol={{ style: { width: 100 } }} preserve initialValues={initValue}>
    //       <div>{steps[current].content}</div>
    //     </Form>
    //   </div>
    // </YmAddPageLayout>
  );
}
